package es.javamyadmin.filtro;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import es.javamyadmin.beans.LoginBean;

@WebFilter("/AdminFiltro")
public class AccesoFiltro implements Filter {

    public AccesoFiltro() {
    }

	public void destroy() {
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpSession sesion = ((HttpServletRequest)request).getSession();
		LoginBean datosLogin = (LoginBean) sesion.getAttribute("datosLogin");
		
		if (datosLogin==null || datosLogin.getAcceso()==null || datosLogin.getAcceso().equals("")){
			
			((HttpServletResponse)response).sendRedirect("../index.jsp");
			
		}else{
			
			if (datosLogin.getAcceso().equals("si")){
				//Puedes pasar!!
				chain.doFilter(request, response);
			}
			else { 
				//No permito acceso
				Cookie login = new Cookie("login", "");
    			login.setMaxAge(0);
    			login.setPath("/");
    			((HttpServletResponse)request).addCookie(login);
				((HttpServletResponse)response).sendRedirect("../index.jsp");
			}
		}
				
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
